package com.imooc.pay.service.impl;

import com.google.gson.Gson;
import com.imooc.pay.Enums.PayPlatformEnum;
import com.imooc.pay.dao.PayInfoMapper;
import com.imooc.pay.pojo.PayInfo;
import com.imooc.pay.service.IPayService;
import com.lly835.bestpay.config.WxPayConfig;
import com.lly835.bestpay.enums.BestPayPlatformEnum;
import com.lly835.bestpay.enums.BestPayTypeEnum;
import com.lly835.bestpay.enums.OrderStatusEnum;
import com.lly835.bestpay.model.PayRequest;
import com.lly835.bestpay.model.PayResponse;
import com.lly835.bestpay.service.BestPayService;
import com.lly835.bestpay.service.impl.BestPayServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @author:枫华
 * @date:2020/2/18
 * @Description:
 */
@Slf4j
@Service
public class PayServiceImpl implements IPayService {

    private final static String QUEUE_PAY_NOTIFY = "payNotify";

    @Autowired
    private BestPayService bestPayService;

    @Autowired
    private PayInfoMapper payInfoMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    public PayResponse create(String orderId, BigDecimal amount,BestPayTypeEnum bestPayTypeEnum) {

        //查询数据库是否有此订单
        PayInfo payInfo = payInfoMapper.selectByOrderNo(Long.parseLong(orderId));

        if(payInfo == null){
            payInfo = new PayInfo(Long.parseLong(orderId),
                    PayPlatformEnum.getByBestPayTypeEnum(bestPayTypeEnum).getCode(),
                    OrderStatusEnum.NOTPAY.name(),
                    amount);
            //装入数据库
            payInfoMapper.insertSelective(payInfo);
        }
        PayRequest payRequest = new PayRequest();
        payRequest.setOrderName("6176209-最好的支付sdk");
        payRequest.setOrderId(orderId);
        payRequest.setOrderAmount(amount.doubleValue());
        payRequest.setPayTypeEnum(bestPayTypeEnum);
        PayResponse response = bestPayService.pay(payRequest);
        log.info("response:{}",response);
        return response;
    }

    @Override
    public String asyncNotify(String notifyData) {

        PayResponse payResponse = bestPayService.asyncNotify(notifyData);
        log.info("payResponse:{}" ,payResponse);


        PayInfo payInfo = payInfoMapper.selectByOrderNo(Long.parseLong(payResponse.getOrderId()));
        if(payInfo == null){
            throw new RuntimeException("通过orderNo查询结果为null："+payResponse.getOrderId());
        }

        if(!payResponse.getPayPlatformEnum().equals(OrderStatusEnum.SUCCESS.getDesc())){
            // 验证金额
            if(payInfo.getPayAmount().compareTo(BigDecimal.valueOf(payResponse.getOrderAmount())) != 0){
                throw new RuntimeException("支付金额和数据库金额不一致："+payResponse.getOrderAmount());
            }
            // 修改订单支付状态
            payInfo.setPlatformNumber(payResponse.getOutTradeNo());
            payInfo.setPlatformStatus(OrderStatusEnum.SUCCESS.name());
            payInfoMapper.updateByPrimaryKeySelective(payInfo);
        }

        amqpTemplate.convertAndSend(QUEUE_PAY_NOTIFY, new Gson().toJson(payInfo));
        //通知微信
        if(payResponse.getPayPlatformEnum() == BestPayPlatformEnum.WX){
            return "<xml>\n"+
                    "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                    "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                    "</xml>";
        }else if(payResponse.getPayPlatformEnum() == BestPayPlatformEnum.ALIPAY){
            return "success";
        }
        throw new RuntimeException("异步通知中错误的支付平台");
    }

    @Override
    public PayInfo queryByOrderId(String orderId) {
        return payInfoMapper.selectByOrderNo(Long.parseLong(orderId));
    }
}
